<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './dept.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { getDeptList,UpdateDept,AddDept } from '@/api/system/dept';

  const { notification } = useMessage();
  const { t } = useI18n();
  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      var update = ''
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        update = data.record
        const apidata = await getDeptList(null);
        const par_menu = {
          id:'0',
          key:'0',
          label:'最上级',
          name:'最上级',
          parentId: "0",
          value: "0"
        }
        apidata.data.push(par_menu)
        const treeData = apidata.data
        updateSchema({
          field: 'parentId',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            // 更新
             values['status'] = parseInt(values['status'])
             values['orderNum'] = values['orderNo']
             values['id'] = update['id']
             delete values['orderNo']
             const update_menu = await UpdateDept(values)
             if(update_menu.code == 200){
                notification.success({
                message: t('sys.update.success'),
                description: t('sys.update.success'),
                duration: 3,
              });
                  closeModal();
                  emit('success');
             }else{
                notification.error({
                message: t('sys.update.error'),
                description: update_menu.msg,
                duration: 3,
              });
             }
            //  组装update数据
          }else{
            // 添加
             values['status'] = parseInt(values['status'])
             values['orderNum'] = values['orderNo']
             delete values['orderNo']
             const update_menu = await AddDept(values)
             if(update_menu.code == 200){
                notification.success({
                message: t('sys.add.addsuccess'),
                description: t('sys.add.addsuccess'),
                duration: 3,
              });
               closeModal();
               emit('success');
             }else{
                notification.error({
                message: t('sys.add.addfail'),
                description: update_menu.msg,
                duration: 3,
              });
             }
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
